package cn.cloudmenu.android.activity;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.cloudmenu.android.CloudMenuApp;
import cn.cloudmenu.android.CoursesWebSocket;
import cn.cloudmenu.android.MenuCourseBean;
import cn.cloudmenu.android.MenuCoverBean;
import cn.cloudmenu.android.MenuOpeningTableBean;
import cn.cloudmenu.android.R;
import cn.cloudmenu.android.UserProfile;


public class Courses extends ListActivity {
	private static final ArrayList<MenuCourseBean> MenuCourses = new ArrayList<MenuCourseBean>();
	private CoursesWebSocket webSocket;
	private MenuOpeningTableBean openingTable;
	private CloudMenuApp cloudMenuApp;
	
	private static class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private String menuImagePath;

		public EfficientAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			menuImagePath = context.getResources().getString(R.string.menu_image_path);
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return MenuCourses.size();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return MenuCourses.get(position);
		}

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.courses_list_item_icon_text, null);
				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.course_name);
				holder.price = (TextView) convertView.findViewById(R.id.course_price);
				holder.icon = (ImageView) convertView.findViewById(R.id.course_icon);
				holder.button = (Button) convertView.findViewById(R.id.order_course_button);
				convertView.setTag(holder);
				// System.out.println("Courses.java holder.button = "+holder.button);
				holder.button.setTag(MenuCourses.get(position));
				holder.icon.setTag(MenuCourses.get(position));
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			MenuCourseBean course = MenuCourses.get(position);
			holder.name.setText(course.getName());
			holder.price.setText(course.getPrice()+"");
			// holder.icon.setImageBitmap(mIcon);
			holder.icon.setImageDrawable(fetch(menuImagePath + course.getSmallLandscapeImagePath()));

			return convertView;
		}

		static class ViewHolder {
			TextView name;
			TextView price;
			ImageView icon;
			Button button;
		}
	}

	private static Drawable fetch(String urlString) {
		try {
			System.out.println("Courses.fetch() urlString = " + urlString);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(urlString);
			HttpResponse response = httpClient.execute(request);
			Drawable drawable = Drawable.createFromStream(response.getEntity().getContent(), "src");
			return drawable;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.courses_list);

		this.cloudMenuApp = (CloudMenuApp)this.getApplicationContext();
		// 从服务器获取菜单菜品分类信息
		MenuCourses.clear();
		this.loadMenuCourses();

		this.openingTable = new MenuOpeningTableBean();
		this.openingTable.setMenuId(getIntent().getIntExtra("menuId", -1));
		this.openingTable.setOpener(getIntent().getStringExtra("opener"));
		this.openingTable.setTableName(getIntent().getStringExtra("tableName"));

		
		setListAdapter(new EfficientAdapter(this));
		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		System.out.println("Courses.onCreate() .............!!!!!!!!!!!!!!!!!!!!!!");
		// 为ListView设置列表项点击监听器
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				System.out.println("Courses.OnItemClickListener() .............!!!!!!!!!!!!!!!!!!!!!!");
				// MenuCategoryBean category = (MenuCategoryBean)
				// parent.getItemAtPosition(position);
				// Intent intent = new Intent(Courses.this, Courses.class);
				// Courses.this.startActivity(intent);
			}
		});
		
		try{
			System.out.println("wwwwwwwwwwwwwwwwwwwwwwww WebSocket 1");
			String websocket_url = this.getResources().getString(R.string.websocket_url);
			WebView webView = new WebView(this);
			//Integer menuId = getIntent().getIntExtra("menuId", -1);
			UserProfile user = ((CloudMenuApp)this.getApplication()).getUser();
			MenuCoverBean menu = ((CloudMenuApp)this.getApplication()).getMenu();
			this.webSocket = new CoursesWebSocket(webView, URI.create(websocket_url), user, menu, this);
			webSocket.connect();
			//webSocket.send("Your message");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 2);
		t1.show();
	}

	public void orderCourse(View view) {
		System.out.println("Courses.orderCourse(view) is called! view.getTag() = " + view.getTag());
		System.out.println("Courses.orderCourse(view) is called! view.getParent() = " + view.getParent());
		System.out.println("Courses.orderCourse(view) is called! view.getParent() = " + view.getParent());
		MenuCourseBean course = (MenuCourseBean)view.getTag();
		this.webSocket.orderCourse(course);
	}
	
	public void orderedList(View view) {
		System.out.println("Courses.orderedList(view) is called! view.getTag() = " + view.getTag());
		Intent intent = new Intent(this, CoursesOrdered.class);
		intent.putExtras(getIntent());
		this.startActivity(intent);
	}
	
	private String message;
	public void setMessage(String message){
		this.message = message;
		cwjHandler.post(updateHeaderMessage);
	}
	public void headerMessage(){
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
		animation.setFillAfter(true);
		TextView header = (TextView) this.findViewById(R.id.courses_list_header);
		header.setText(message);
		header.startAnimation(animation);		
	}

	public void viewDetail(View view) {
		System.out.println("Courses.viewDetail(view) is called! view.getTag() = " + view.getTag());
		System.out.println("Courses.viewDetail(view) is called! view.getParent() = " + view.getParent());
		System.out.println("Courses.viewDetail(view) is called! view.getParent() = " + view.getParent());
	}

	private boolean loadMenuCourses() {
		String href = getResources().getString(R.string.menu_courses);
		Integer menuId = getIntent().getIntExtra("menuId", -1);
		Integer tagId = getIntent().getIntExtra("tagId", -1);
		//if (menuId.equals(-1L) || tagId.equals(-1)) return false;
		href = href + menuId;// + "&tagId=" + tagId;
		System.out.println("Courses.loadMenuCourses() href = " + href);
		HttpPost request = new HttpPost(href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据
			String retSrc = EntityUtils.toString(httpResponse.getEntity());

			// 生成 JSON 对象
			JSONArray courses = new JSONArray(retSrc);
			System.out.println("Courses.loadMenuCourses() courses.length = " + courses.length());
			if (courses.length() < 1) {
				Intent intent = new Intent(this, FavoriteMenu.class);
				this.startActivity(intent);
				return false;
			} else {
				for (int i = 0; i < courses.length(); i++) {
					JSONObject course = courses.getJSONObject(i);
					MenuCourseBean c = new MenuCourseBean();
					c.setId(course.getInt("id"));
					c.setTagId(course.getInt("tagId"));
					c.setMenuId(course.getInt("menuId"));
					c.setName(course.getString("name"));
					c.setPrice(course.getInt("price"));
					c.setCreateTime(new Date(course.getLong("createTime")));
					c.setUpdateTime(new Date(course.getLong("updateTime")));
					List<String> portraitImages = new ArrayList<String>();
					List<String> landscapeImages = new ArrayList<String>();
					JSONArray limages = course.getJSONArray("landscapeImages");
					JSONArray pimages = course.getJSONArray("portraitImages");
					for (int j = 0; j < limages.length(); j++) {
						landscapeImages.add(limages.getString(j));
					}
					c.setLandscapeImages(landscapeImages);
					for (int j = 0; j < pimages.length(); j++) {
						portraitImages.add(pimages.getString(j));
					}
					c.setPortraitImages(portraitImages);
					if(c.getTagId().equals(tagId)){
						MenuCourses.add(c);
					}
					this.cloudMenuApp.getAllCoursesInCurrentMenu().put(c.getId(), c);
				}
				return true;
			}
		} catch (Exception e) {
			displayMessage(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
	final Handler cwjHandler = new Handler();

	final Runnable updateHeaderMessage = new Runnable() {
		public void run() {
	    	headerMessage();
	    }
	};

}